import { geo_api } from "@/api/home";
import { AppData } from "./app";

export const getLocation = (
  success: (lngLat: { lng: number; lat: number }) => void,
  cancel?: () => void,
  type?: "gcj02" | "wgs84"
) => {
  uni.getLocation({
    type: type || "gcj02",
    success: resp => {
      console.log("getLocation success", resp);
      success({ lng: resp.longitude, lat: resp.latitude });
    },
    fail: error => {
      console.error("getLocation fail", error);
      cancel?.();
    },
  });
};

/**
 * 获取当前全局位置信息
 * @param callback
 * @param fail
 */
export const getGlobalPosition = (
  callback: (position: { cityId: string; cityName: string }) => void,
  fail?: () => void
) => {
  const positionData = AppData.positionData;

  if (positionData.cityId) return callback(positionData);

  getLocation(lngLat => {
    geo_api({ lng: lngLat.lng, lat: lngLat.lat })
      .then((resp: any) => {
        console.log("get_geo_api", resp);
        AppData.positionData = {
          cityId: resp.city_id,
          cityName: resp.city_name,
        };

        callback(AppData.positionData);
      })
      .catch(fail);
  }, fail);
};
